package com.atguigu.lease.web.app.custom.interceptor;


import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginContext;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserInfoMapper userInfoManager;

    //校验用户是否登录   有token才表示登录

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("access_token");
        if (!StringUtils.hasLength(token)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        Long userId = JwtUtil.getUserId(token);
        //使用threadLocal共享用户信息
        UserInfo userInfo = userInfoManager.selectById(userId);
        LoginUserContext.setLoginUser(new LoginUser(userInfo.getId(),userInfo.getPhone()));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}